package com.example.util;

/**
 * @author wangjinlong
 * @version 1.0
 * @date 2021/6/16 16:42
 */
import com.google.common.collect.Lists;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TimeRangeUtil {

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        List<Long> timeList = getTime2();
        long up = 180;
        long down = 120;
        List<List<Long>> timeRange = getTimeRange(timeList, up, down);
        timeRange.forEach(System.out::println);
        for (List<Long> list : timeRange) {
            for (Long aLong : list) {
                date.setTime(aLong * 1000);
                System.out.print(format.format(date) + " ");
            }
            System.out.println("");
        }
    }

    // 对时间集合分段
    public static List<List<Long>> getTimeRange(List<Long> timeList, long up, long down){
        List<List<Long>> timeRangeList = new ArrayList<>();
        int index = 0;
        timeRangeList.add(Lists.newArrayList(timeList.get(0) - up, timeList.get(0) + down));
        do {
            long s_time = timeList.get(0);
            index = getNext(timeList, down, s_time);
            if (index > -1) {
                Long next = timeList.get(index);
                long max = Math.max(timeRangeList.get(timeRangeList.size() - 1).get(1) + 1, next - up);
                timeRangeList.add(Lists.newArrayList(max, next + down));
                timeList = timeList.subList(index, timeList.size());
            }
        } while (index > -1);
        return timeRangeList;
    }

    public static int getNext(List<Long> timeList, long down, long time){
        for(int i=0; i < timeList.size(); i++){
            Long aLong = timeList.get(i);
            if (aLong > time + down) {
                return i;
            }
        }
        return -1;
    }

    public static List<Long> getTime2(){
        return Lists.newArrayList(
                1623722113L,
                1623722396L,
                1623723213L,
                1623723931L,
                1623724057L,
                1623724171L,
                1623727779L
        );
    }

    /**
     * 2021-06-15 09:55:13
     * 2021-06-15 09:59:56
     * 2021-06-15 10:13:33
     * 2021-06-15 10:25:31
     * 2021-06-15 10:29:31
     * 2021-06-15 11:29:39
     */
    public static List<Long> getTimeList() throws InterruptedException {
        List<Long> timeList = new ArrayList<>();
        for (int i=0; i < 50; i++) {
            long time = System.currentTimeMillis();
            timeList.add(time);
            Thread.sleep((i % 10) * 100);
        }
        timeList.forEach(System.out::println);
        return timeList;
    }
}